from urllib import request,parse
import json

url = 'http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule'

# 定义fanyi函数
def fanyi(keyword):
    
    # 定义请求参数
    data = {
		 "i":keyword,
		"from":"AUTO",
		"to":"AUTO",
		"smartresult":"dict",
		"client":"fanyideskweb",
		"salt":'f',
		"sign":'sign',
		"doctype":"json",
		"version":"2.1",
		"keyfrom":"fanyi.web",
		"action":"FY_BY_REALTIME",
		"typoResult":"false"
		 }

    # 请求参数转码

    data = parse.urlencode(data)

    # 封装headers头部信息

    headers = {
		'Content-Length' : len(data)
		}
    # 发送请求，爬取数据

    req = request.Request(url=url,data=bytes(data,encoding='utf-8'),headers=headers)
    res = request.urlopen(req)

    # 解析结果并输出

    str_json = res.read().decode('utf-8') # 解析数据，并解码输出的是json格式的数据
    myjson = json.loads(str_json) # json格式数据转字典格式
    info = myjson['translateResult'][0][0]['tgt']
    print(info)
if __name__=='__main__':
    while True:
        keyword = input("请输入翻译的单词:")
        if keyword == 'q':
            break
        fanyi(keyword)
